package com.example.srpingsecurityoauth2.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName UserController
 * @Description
 * @Author gqz
 * @Date 2021/12/30 16:02
 * @Version 1.0
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${oauth2.client.id}")
    private String clientId;

    @Value("${oauth2.client.scope}")
    private String scope;

    @Value("${oauth2.client.registered-redirect-uri}")
    private String redirectUri;

    @Value("${oauth2.client.type}")
    private String type;

    //获取token信息
    @RequestMapping("/getToken")
    public JSONObject getToke(String code){
        String url="http://localhost:8081/oauth/token";
        JSONObject body=new JSONObject();
        body.put("grant_type",type);
        body.put("code", code);
        body.put("client_id", clientId);
        body.put("redirect_uri", redirectUri);
        body.put("scope", scope);
        JSONObject result = restTemplate.postForObject(url, body, JSONObject.class);
        return result;
    }

    //获取当前用户信息
    @GetMapping("/getUserInfo")
    public Object getUserInfo(Authentication authentication){
        Object principal = authentication.getPrincipal();
        return principal;
    }
}
